const mongoose=require('mongoose');
const Cate = require('../models/cate.model');

exports.create=function(req,res,next){
    const Cates = new Cate(req.body);
    Cates.save().then(data => {
        res.json(data);
    });
}

exports.updata=function(req,res,next){
    var id = req.params.id;
    Cate.findByIdAndUpdate(id,{$set:req.body},{new:false})
    .then(data=>{
        res.json(data);
    })
}

exports.get=function(req,res,next){
    var id = req.params.id;
    Cate.findById(id)
    .then(data=>{
        res.json(data);
    })
}

exports.removeIt=function(req,res,next){
    var id = req.params.id;
    for(var i=0;i<id.split(',').length;i++){
        removes(id.split(',')[i])
    }
    res.json({'message': "删除多个记录成功"});
}

function removes(id){
    Cate.findByIdAndDelete(id).then(() => { })
    Cate.find({ parentId: id }).then(data => {
        if (data && data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                removes(data[i]._id)
            }
        }
    })
}

function reverseTree(data,parentID){
    var result = [], temp;
    var data   = JSON.parse(JSON.stringify(data));
    for(var i in data){
        if(data[i].parentId===parentID){
            data[i].title = data[i].text
            result.push(data[i]);

            temp = reverseTree(data,data[i]._id)
            if(temp.length>0){
                data[i].children = temp;
            }
        }
    }
    return result;
}

exports.list=function(req,res,next){
    var type = req.params.type;
    Cate.find({type:type}).then(data=>{
        //res.json(data)
        res.json(reverseTree(data,null));
    })
}